#include "PhoneDevice.h"
#include <string.h>
#include <iostream>
PhoneDevice::PhoneDevice(QObject *parent) :
    BaseInterface<PhoneDevice>(parent)
{
    m_pInstance = this;
    cloudProtocol = new CloudProtocol(this);
    this->registerProtocol(cloudProtocol);
    qDebug()<<"PhoneDevice runing-1";
    Package package;
    QByteArray head;
    head.append(0xf0);
    head.append(0x0f);
    package.setHead(head.mid(0,2));
    package.setVersion(0x01);
    package.setId(0x01);
    PortStruct portstruct;
    portstruct.setIp("255.255.255.255");
    portstruct.setType("UDP");
    portstruct.setName("PhoneDeviceUDP");
    portstruct.setPort(10000);
    package.setPortStruct(portstruct);
    m_WaitBackMap.insert(0x46,package);
    m_WaitBackMap.insert(0x5b,package);
    m_WaitBackMap.insert(0x5E,package);
    registerCmdHandler(AppSearchCmd::FunctionCode,AppSearchCmd::staticMetaObject, &PhoneDevice::appSearchCmdHandle);
    registerCmdHandler(HandshakeCmd::FunctionCode,HandshakeCmd::staticMetaObject, &PhoneDevice::handshakeCmdHandle);
    registerCmdHandler(HeartbeatCmd::FunctionCode,HeartbeatCmd::staticMetaObject, &PhoneDevice::heartBeatCmdHandle);
    registerCmdHandler(UserLoginCmd::FunctionCode,UserLoginCmd::staticMetaObject, &PhoneDevice::userLoginCmdHandle);
    registerCmdHandler(CloudControlPointCmd::FunctionCode,CloudControlPointCmd::staticMetaObject, &PhoneDevice::controlPointCmdHandle);
    registerCmdHandler(DownloadPointListRequestCmd::FunctionCode,DownloadPointListRequestCmd::staticMetaObject, &PhoneDevice::downloadPointListRequestCmdHandle);
    registerCmdHandler(CustomSceneControlCmd::FunctionCode,CustomSceneControlCmd::staticMetaObject, &PhoneDevice::customSceneControlCmdHandle);
    registerCmdHandler(UpdatePointCmd::FunctionCode,UpdatePointCmd::staticMetaObject, &PhoneDevice::updatePointCmdHandle);

    registerCmdHandler(SetUPZigbee3Cmd::FunctionCode,SetUPZigbee3Cmd::staticMetaObject, &PhoneDevice::SetUPZigbee3CmdHandle);
    registerCmdHandler(AllowToJoinZigbee3Cmd::FunctionCode,AllowToJoinZigbee3Cmd::staticMetaObject, &PhoneDevice::AllowToJoinZigbee3CmdHandle);
    registerCmdHandler(ApplyToQuitZigbee3Cmd::FunctionCode,ApplyToQuitZigbee3Cmd::staticMetaObject, &PhoneDevice::ApplyToQuitZigbee3CmdHandle);
    //registerCmdHandler(ZBQuitFeedBackCmd::FunctionCode,ZBQuitFeedBackCmd::staticMetaObject, &PhoneDevice::ZBQuitFeedBackCmdHandle);
    registerCmdHandler(QueryZigbee3PropertiesCmd::FunctionCode,QueryZigbee3PropertiesCmd::staticMetaObject, &PhoneDevice::QueryZigbee3PropertiesCmdHandle);
    registerCmdHandler(SetZigbee3DataCmd::FunctionCode,SetZigbee3DataCmd::staticMetaObject, &PhoneDevice::SetZigbee3DataCmdHandle);

    registerCmdHandler(Zigbee3QueryDataCmd::FunctionCode,Zigbee3QueryDataCmd::staticMetaObject, &PhoneDevice::Zigbee3QueryDataCmdHandle);
    registerCmdHandler(QueryOtherEquipmentCmd::FunctionCode,QueryOtherEquipmentCmd::staticMetaObject, &PhoneDevice::QueryOtherEquipmentHandle);

     registerCmdHandler(OPInfraredToLearnCmd::FunctionCode,OPInfraredToLearnCmd::staticMetaObject, &PhoneDevice::ZB3OPInfraredToLearnHandle);
     registerCmdHandler(TestInfraredToLearnCmd::FunctionCode,TestInfraredToLearnCmd::staticMetaObject, &PhoneDevice::ZB3OPInfraredToTestHandle);
     registerCmdHandler(SaveInfraredToLearnCmd::FunctionCode,SaveInfraredToLearnCmd::staticMetaObject, &PhoneDevice::ZB3OPInfraredToSaveHandle);

   registerFuncHandler(UpdatePointFunc::FunctionCode, &PhoneDevice::updatePointFuncHandle);
   registerFuncHandler(LogicCloudDataFunc::FunctionCode, &PhoneDevice::LogicCloudDataFuncHandle);
    registerCmdHandler(PhoneToAllocationCmd::FunctionCode,PhoneToAllocationCmd::staticMetaObject, &PhoneDevice::phoneToallocationCmdHandle);
    qDebug()<<"PhoneDevice runing-2";
}

void PhoneDevice::clientDisconnectedSlot(PortStruct source)
{
    if(!isLegalClient(source))
    {
        return;
    }
    clientList.removeOne(source);
}

bool PhoneDevice::isLegalClient(PortStruct source)
{
    bool isLegal = false;
    if(clientList.indexOf(source) != -1)
    {
        isLegal = true;
    }
    return isLegal;
}

void PhoneDevice::appSearchCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    AppSearchResponseCmd *appSearchResponseCmd = new AppSearchResponseCmd();

    quint16 cmdId = sharedCmd->cmdId();
    appSearchResponseCmd->setCmdId(cmdId);

    MacXml *macXml = MacXml::getInstance();
    QString mac = macXml->mac();
    appSearchResponseCmd->setMac(mac);

    quint16 portNumber = 0;
    foreach (const BasePort *port , m_portList)
    {
         if(port->portParam().type() == "TCPServer")
         {
             portNumber = port->portParam().port();
         }
    }
    appSearchResponseCmd->setPort(portNumber);

    UserListXml *userListXml = UserListXml::getInstance();
    QList<UserStruct> userList = userListXml->userList();
    appSearchResponseCmd->setUserList(userList);

    QSharedPointer<BaseCmd> shareAppSearchResponsedCmd(appSearchResponseCmd);
    this->sendCmd(source,shareAppSearchResponsedCmd);
}

void PhoneDevice::handshakeCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    HandshakeCmd *handshakeCmd = qobject_cast<HandshakeCmd*>(sharedCmd.data());

     quint16 cmdId = sharedCmd->cmdId();

    int aesLength = handshakeCmd->ivecRandom().length();
    if(aesLength != 16)
    {
        ResponseCmd *responseCmd = new ResponseCmd();
        responseCmd->setCmdId(cmdId);
        responseCmd->setResponseCode(CloudProtocol::AesLengthError);
        QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
        this->sendCmd(source,sharedResponseCmd);
        return;
    }

    quint8 clientType = handshakeCmd->clientType();
    if((clientType != 0) &&(clientType != 1) && (clientType != 2))
    {
        ResponseCmd *responseCmd = new ResponseCmd();
        responseCmd->setCmdId(cmdId);
        responseCmd->setResponseCode(CloudProtocol::ClientTypeError);
        QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
        this->sendCmd(source,sharedResponseCmd);
        return;
    }

    clientList.append(source);
    HandshakeSucceedCmd *handshakeSucceedCmd = new HandshakeSucceedCmd();
    handshakeSucceedCmd->setCmdId(cmdId);
    QByteArray serverRandom;
    serverRandom.resize(16);

    System *system = System::getInstance();

    handshakeSucceedCmd->setServerRandom(serverRandom);
    handshakeSucceedCmd->setHeartbeatIntervalTime(30000);
    handshakeSucceedCmd->setHeartbeatTimeoutCount(3);
    handshakeSucceedCmd->setHeartbeatTimeoutTime(3000);
    handshakeSucceedCmd->setServerTime(system->timeBCD());
    QSharedPointer<BaseCmd> sharedHandshakeSucceedCmd(handshakeSucceedCmd);
    this->sendCmd(source,sharedHandshakeSucceedCmd);
}

void PhoneDevice::heartBeatCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    if(!isLegalClient(source))
    {
        return;
    }
    HeartbeatCmd *heartBeatCmd = new HeartbeatCmd();
    quint16 cmdId = sharedCmd->cmdId();
    heartBeatCmd->setCmdId(cmdId);
    QSharedPointer<BaseCmd> sharedHeartBeatCmd(heartBeatCmd);
    this->sendCmd(source,sharedHeartBeatCmd);
}

void PhoneDevice::userLoginCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    if(!isLegalClient(source))
    {
        return;
    }

    quint16 cmdId = sharedCmd->cmdId();

    UserLoginCmd *userLoginCmd = qobject_cast<UserLoginCmd*>(sharedCmd.data());

    QByteArray loginTime = userLoginCmd->loginTime();
    if(loginTime.size() < 7)
    {
        ResponseCmd *responseCmd = new ResponseCmd();
        responseCmd->setCmdId(cmdId);
        responseCmd->setResponseCode(CloudProtocol::LoginTimeError);
        QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
        this->sendCmd(source,sharedResponseCmd);
        return;
    }

    QString account = userLoginCmd->account();
    if(account.isEmpty())
    {
        ResponseCmd *responseCmd = new ResponseCmd();
        responseCmd->setCmdId(cmdId);
        responseCmd->setResponseCode(CloudProtocol::AccountNullError);
        QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
        this->sendCmd(source,sharedResponseCmd);
        return;
    }

    QString password = userLoginCmd->password();
    if(password.isEmpty())
    {
        ResponseCmd *responseCmd = new ResponseCmd();
        responseCmd->setCmdId(cmdId);
        responseCmd->setResponseCode(CloudProtocol::PasswordNullError);
        QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
        this->sendCmd(source,sharedResponseCmd);
        return;
    }

    UserListXml *userListXml = UserListXml::getInstance();
    QList<UserStruct> userList = userListXml->userList();

    int index;
    for(index=0; index<userList.size(); index++)
    {
        UserStruct user = userList.at(index);
        if(user.account() == account)
        {
            if(user.password() == password)
            {
                MacXml *macXml = MacXml::getInstance();
                QString mac = macXml->mac();

                UserListXml *userListXml = UserListXml::getInstance();
                QList<UserStruct> userList = userListXml->userList();

                UesrLoginSucceedCmd *uesrLoginSucceedCmd = new UesrLoginSucceedCmd();
                uesrLoginSucceedCmd->setCmdId(cmdId);
                uesrLoginSucceedCmd->setMac(mac);
                uesrLoginSucceedCmd->setControlProtocol(1);
                uesrLoginSucceedCmd->setUserList(userList);
                QSharedPointer<BaseCmd> sharedUesrLoginSucceedCmd(uesrLoginSucceedCmd);
                this->sendCmd(source,sharedUesrLoginSucceedCmd);

                CurrentPointStore *currentPointStore = CurrentPointStore::getInstance();
                QList<ControlPointStruct> currentPointList = currentPointStore->currentPointList();
                UpdatePointCmd *updatePointCmd = new UpdatePointCmd();
                updatePointCmd->setUpdatePointList(currentPointList);
                QSharedPointer<BaseCmd> sharedUpdatePointCmd(updatePointCmd);
                this->sendCmd(source,sharedUpdatePointCmd);

                return;
            }
            else
            {
                ResponseCmd *responseCmd = new ResponseCmd();
                responseCmd->setCmdId(cmdId);
                responseCmd->setResponseCode(CloudProtocol::PasswordWrongError);
                QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
                this->sendCmd(source,sharedResponseCmd);
                return;
            }
        }
    }
    if(index == userList.size())
    {
        ResponseCmd *responseCmd = new ResponseCmd();
        responseCmd->setCmdId(cmdId);
        responseCmd->setResponseCode(CloudProtocol::AccountUnboundError);
        QSharedPointer<BaseCmd> sharedResponseCmd(responseCmd);
        this->sendCmd(source,sharedResponseCmd);
        return;
    }

}

void PhoneDevice::controlPointCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    if(!isLegalClient(source))
    {
        return;
    }
    CloudControlPointCmd *cloudControlPointCmd = qobject_cast<CloudControlPointCmd*>(sharedCmd.data());
    int address = cloudControlPointCmd->address();
    int value = cloudControlPointCmd->value();

    ControlPointFunc *pointControlFunc = new ControlPointFunc();
    ControlPointStruct sourcePoint;
    sourcePoint.setAddress(address);
    sourcePoint.setValue(value);
    SavePointXml *savePointXml =SavePointXml::getInstance();
    savePointXml->SavePointData(address,value);
    QString stata="Read-Phone";
    qDebug()<<"read-Phone------------------";
    savePointXml->JoinSystemList(address,value,stata);
    QList<ControlPointStruct> sourcePointList;
    sourcePointList.append(sourcePoint);
    pointControlFunc->setSourceDevice(this->name());
    pointControlFunc->setSourcePointList(sourcePointList);
    QSharedPointer<BaseFunc> sharedPointControlFunc(pointControlFunc);
    emit transferFuncSignal(sharedPointControlFunc);
}

void PhoneDevice::downloadPointListRequestCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    if(!isLegalClient(source))
    {
        return;
    }

    quint16 cmdId = sharedCmd->cmdId();
    CurrentPointStore *currentPointStore = CurrentPointStore::getInstance();
    QList<ControlPointStruct> currentPointList = currentPointStore->currentPointList();

    DownloadPointListCmd *downloadPointListCmd = new DownloadPointListCmd();
    downloadPointListCmd->setCmdId(cmdId);
    downloadPointListCmd->setDownloadPointList(currentPointList);

    QSharedPointer<BaseCmd> sharedDownloadPointListCmd(downloadPointListCmd);
    sendCmd(source,sharedDownloadPointListCmd);

}

void PhoneDevice::customSceneControlCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(source);
     qDebug()<<"[PhoneDevice::customSceneControlCmdHandle] ";
    CustomSceneControlCmd *customSceneControlCmd = qobject_cast<CustomSceneControlCmd*>(sharedCmd.data());
    quint64 sceneId = customSceneControlCmd->sceneId();
    CustomSceneXml *customSceneXml = CustomSceneXml::getInstance();
    QList<ActionStruct> actionList = customSceneXml->actionList(sceneId);

    if(!actionList.isEmpty())
    {
        QList<ControlPointStruct> sourcePointList;
        for(int i=0; i<actionList.size(); i++)
        {
            ActionStruct action = actionList.at(i);
            ControlPointStruct sourcePoint;
            int address = action.address();
            int value   = action.functionValue();
            quint64 delaytime=action.delayTime()/100;
            sourcePoint.setAddress(address);
            sourcePoint.setValue(value);
            sourcePoint.setDelayTime(delaytime);
            sourcePointList.append(sourcePoint);
        }

        ControlPointFunc *pointControlFunc = new ControlPointFunc();
        pointControlFunc->setSourcePointList(sourcePointList);
        QSharedPointer<BaseFunc> sharedPointControlFunc(pointControlFunc);
        emit transferFuncSignal(sharedPointControlFunc);
    }
}

void PhoneDevice::updatePointCmdHandle(PortStruct source, QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(source);
    UpdatePointCmd *updatePointCmd = qobject_cast<UpdatePointCmd*>(sharedCmd.data());
    QList<ControlPointStruct> updatePointList = updatePointCmd->updatePointList();
    CurrentPointStore *currentPointStore = CurrentPointStore::getInstance();
    currentPointStore->insert(updatePointList);
}


void PhoneDevice::updatePointFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{
    UpdatePointFunc *updatePointFunc = qobject_cast<UpdatePointFunc*>(sharedFunc.data());
    QList<ControlPointStruct> updatePointList;
    updatePointList = updatePointFunc->updatePointList();
    if(updatePointList.isEmpty())
    {
        return;
    }

    for(int i=0; i<clientList.size(); i++)
    {
        PortStruct target = clientList.at(i);
        UpdatePointCmd *updatePointCmd = new UpdatePointCmd();
        updatePointCmd->setUpdatePointList(updatePointList);
        QSharedPointer<BaseCmd> sharedUpdatePointCmd(updatePointCmd);
        sendCmd(target,sharedUpdatePointCmd);
    }

}


void PhoneDevice::SetUPZigbee3CmdHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(sharedCmd);
    Q_UNUSED(target);
  //  qDebug()<<"SetUPZB3-";
    Package package;
    package.clear();

    QByteArray head = QByteArray::fromHex(QString("A5AA5A").toLatin1());
    QByteArray CmdData1;
    QByteArray CmdData2;
    CmdData1.append(head);
    CmdData2.append(head);
    package.setFunction(0xA1);
    CmdData1.append(DataTypeConver::intToByteArray(package.function(),1));
    package.setFunction(0xA4);
    CmdData2.append(DataTypeConver::intToByteArray(package.function(),1));
    PortStruct targeter;
    foreach (const BasePort *port , m_portList)
    {
     //   qDebug()<<"PortType="<<port->portParam().type();
    //    qDebug()<<"PortName="<<port->portParam().name();
         if((port->portParam().type() == "UART" && port->portParam().name() == "Zigbee"))
         {
             targeter = port->portParam();
         //    qDebug()<<"setport-";
         }
    }
     emit sendDataSignal(targeter,CmdData2);
    QElapsedTimer delayTimer;
    delayTimer.start();

    while(delayTimer.elapsed()<=1000);
    emit sendDataSignal(targeter,CmdData1);
}


void PhoneDevice::AllowToJoinZigbee3CmdHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(sharedCmd);
    Q_UNUSED(target);
  //  qDebug()<<"SetUPZB3-";
    Package package;
    package.clear();

    QByteArray head = QByteArray::fromHex(QString("A5AA5A").toLatin1());
    QByteArray CmdData1;
    CmdData1.append(head);
    package.setFunction(0xA2);
    CmdData1.append(DataTypeConver::intToByteArray(package.function(),1));
    PortStruct targeter;
    foreach (const BasePort *port , m_portList)
    {
         if((port->portParam().type() == "UART" && port->portParam().name() == "Zigbee"))
         {
             targeter = port->portParam();

         }
    }
     emit sendDataSignal(targeter,CmdData1);
}

void PhoneDevice::ApplyToQuitZigbee3CmdHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
  ApplyToQuitZigbee3Cmd *applyToQuitZigbee3Cmd = qobject_cast<ApplyToQuitZigbee3Cmd*>(sharedCmd.data());
  Package package;
  package=applyToQuitZigbee3Cmd->toPackage();
  QByteArray CmdData1;
  QByteArray Cmdnwk;
  Cmdnwk=package.body().toHex().toUpper();
  QByteArray head = QByteArray::fromHex(QString("41").toLatin1());
  CmdData1.append(head);
  CmdData1.append(package.body());
  CmdData1.append(0x14);
  PortStruct targeter;
  Zigbee3ListXml *zigbee3ListXml = Zigbee3ListXml::getInstance();


  foreach (const BasePort *port , m_portList)
  {
       if((port->portParam().type() == "UART" && port->portParam().name() == "Zigbee"))
       {
           targeter = port->portParam();

       }
  }
   emit sendDataSignal(targeter,CmdData1);
//  package.clear();
  package.setId(applyToQuitZigbee3Cmd->cmdID());
  package.setPortStruct(target);
  m_WaitBackMap.insert(0x43,package);
  //qDebug()<<"body="<<Cmdnwk;
  //qDebug()<<"strbody="<<QString(Cmdnwk);
  if(zigbee3ListXml->SetDelete(QString(Cmdnwk))==true)
  {
      QByteArray Data;
      Data.append(package.body());
      Data.append(0x02);
      LogicCloudDataFunc *logicCloudDataFunc=new  LogicCloudDataFunc();
      logicCloudDataFunc->setData(Data);
      logicCloudDataFunc->setDataFunctionCode(0x43);
      logicCloudDataFunc->setSourceDevice(this->name());
      QSharedPointer<BaseFunc> sharedlogicCloudDataFuncFunc(logicCloudDataFunc);
      emit transferFuncSignal(sharedlogicCloudDataFuncFunc);
  }
}

void PhoneDevice::QueryZigbee3PropertiesCmdHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
    QueryZigbee3PropertiesCmd *queryZigbee3PropertiesCmd = qobject_cast<QueryZigbee3PropertiesCmd*>(sharedCmd.data());
    Package package;
    package.clear();
    package.setId(queryZigbee3PropertiesCmd->cmdID());
    package.setPortStruct(target);
    QByteArray head = QByteArray::fromHex(QString("A5AA5A").toLatin1());
    QByteArray CmdData1;
    CmdData1.append(head);
    package.setFunction(0xA5);
    CmdData1.append(DataTypeConver::intToByteArray(package.function(),1));
    PortStruct targeter;
    foreach (const BasePort *port , m_portList)
    {
         if((port->portParam().type() == "UART" && port->portParam().name() == "Zigbee"))
         {
             targeter = port->portParam();

         }
    }
    m_WaitBackMap.insert(0x45,package);
    emit sendDataSignal(targeter,CmdData1);
}


void PhoneDevice::SetZigbee3DataCmdHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(target);
    SetZigbee3DataCmd *setZigbee3DataCmd = qobject_cast<SetZigbee3DataCmd*>(sharedCmd.data());

    Zigbee3ListXml *zigbee3ListXml = Zigbee3ListXml::getInstance();
    setZigbee3DataCmd->zigbee3Struct().nwk();
    zigbee3ListXml->SetData(setZigbee3DataCmd->zigbee3Struct());
    qDebug()<<"setzigbee3.jpg";
    QByteArray bodyData;
    bodyData.append(setZigbee3DataCmd->zigbee3Struct().nwk());
    bodyData.append(0x01);
    Package package;
    QByteArray head;
    head.append(0xf0);
    head.append(0x0f);
    package.setHead(head.mid(0,2));
    package.setVersion(0x01);
    package.setId(setZigbee3DataCmd->getcmdid());
    package.setFunction(0x4A);
    package.setPortStruct(target);
    package.setBody(bodyData);
   QByteArray sendData= cloudProtocol->generateData(package);
    emit sendDataSignal(target,sendData);
}

void PhoneDevice::Zigbee3QueryDataCmdHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
  Zigbee3QueryDataCmd *zigbee3QueryDataCmd = qobject_cast<Zigbee3QueryDataCmd*>(sharedCmd.data());
  Zigbee3ListXml *zigbee3ListXml = Zigbee3ListXml::getInstance();
  QList<Zigbee3Struct> zigbee3List=zigbee3ListXml->zigbee3List();
  quint8 listnum=zigbee3ListXml->zigbee3List().size();
  quint16 cmdid=zigbee3QueryDataCmd->getcmdid();
  //qDebug()<<"listnum="<<listnum;
  //qDebug()<<"cmdid="<<cmdid;
  quint16 a=0x00;
  foreach(Zigbee3Struct zigbeestruct,zigbee3List)
  {
        //qDebug()<<"zigbee3="<<zigbeestruct.nwk();
        //qDebug()<<"zigbeenamesize"<<zigbeestruct.name().size();

        QByteArray getData;
        QList<ControlPointStruct> pointStruct=zigbeestruct.pointList();
        getData.append(listnum>>8);
        getData.append(listnum);
        getData.append(zigbeestruct.nwk());
        getData.append(zigbeestruct.mac());
        getData.append(zigbeestruct.type());
        getData.append(zigbeestruct.name().toUtf8().size()>>8);
        getData.append(zigbeestruct.name().toUtf8().size());
        getData.append(zigbeestruct.name());
        getData.append(a);
        foreach(ControlPointStruct Pointstruct,pointStruct)
        {
            getData.append(Pointstruct.address()>>8);
            getData.append(Pointstruct.address());
        }
         getData.append(a);
         getData.append(a);
         getData.append(a);
         getData.append(a);
         getData.append(a);
         getData.append(a);
         getData.append(a);
         getData.append(a);
         getData.append(a);

        Package queryDataPackage;
        queryDataPackage.setBody(getData);
        queryDataPackage.setLength(getData.size());
        queryDataPackage.setFunction(0x48);
        queryDataPackage.setId(cmdid);
        QByteArray sendData=cloudProtocol->generateData(queryDataPackage);
        emit sendDataSignal(target,sendData);
  }

}

void PhoneDevice::ZB3OPInfraredToLearnHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
   Q_UNUSED(target);
   OPInfraredToLearnCmd *zigbee3OPInfraredToLearn = qobject_cast<OPInfraredToLearnCmd*>(sharedCmd.data());
   QString NWK=zigbee3OPInfraredToLearn->m_nwk;
   quint16 Addr=zigbee3OPInfraredToLearn->m_addr;


   Zigbee3InfraredXml *zigbee3InfraredXml = Zigbee3InfraredXml::getInstance();
   Zigbee3ListXml *zigbee3ListXml = Zigbee3ListXml::getInstance();
   quint8 ZigbeeVersion=zigbee3ListXml->ZigbeeVersion().toHex().toInt(0,10);
   Zigbee3InfraredStruct InfraredStruct;
   InfraredStruct.m_nwk=zigbee3OPInfraredToLearn->m_nwk;
   InfraredStruct.m_PointValue=zigbee3OPInfraredToLearn->m_addr;
    qDebug()<<"InfraredStruct.m_nwk="<<NWK;
    qDebug()<<"ADDR="<<Addr;
    QByteArray Infraredid=zigbee3InfraredXml->getInfraredID(Addr);


    Package package;
    package.setBody(Infraredid);
    package.setFunction(0xDC);



    QByteArray InfraredData=zigbee3InfraredXml->generateData(package);

    InfraredStruct.m_data=Infraredid;

    zigbee3InfraredXml->CopyInfrared.insert(Addr,InfraredStruct);
    QByteArray ZBCmd;
    QByteArray ZBData;
    if(ZigbeeVersion!=5)
    {
       ZBCmd.append(0x51);
       ZBCmd.append(QByteArray::fromHex(NWK.toLatin1()));
       ZBCmd.append(0x01);
       ZBCmd.append((char)0x00);
       ZBCmd.append((char)0x00);
       ZBCmd.append(0X02);
       ZBCmd.append(0x0c);
       ZBCmd.append(0X41);
       ZBCmd.append(0X42);
       ZBCmd.append(InfraredData.size());
       ZBCmd.append(InfraredData);
       ZBCmd.append(0x15);
    }
    else if(ZigbeeVersion==5)
    {
        QByteArray getNewnwk;
        getNewnwk.append(zigbee3OPInfraredToLearn->m_nwk.mid(2,1));
        getNewnwk.append(zigbee3OPInfraredToLearn->m_nwk.mid(3,1));
        getNewnwk.append(zigbee3OPInfraredToLearn->m_nwk.mid(0,1));
        getNewnwk.append(zigbee3OPInfraredToLearn->m_nwk.mid(1,1));
        QString newNWK;
        newNWK=getNewnwk;
        qDebug()<<"newNWK="<<newNWK;
        ZBCmd.append(0x68);
        ZBCmd.append(char(0x01));
        ZBCmd.append(char(0x00));
        ZBCmd.append(char(0x01));

        ZBData.append(char(0x00));
        ZBData.append(char(0xf1));
        ZBData.append(QByteArray::fromHex(newNWK.toLatin1()));
        ZBData.append(InfraredData.size());
        ZBData.append(InfraredData);
        if(ZBData.size()<0xff)
        {
            ZBCmd.append(char(0x00));
        }

        ZBCmd.append(ZBData.size());
        ZBCmd.append(ZBData);
        quint16 Cheaknum=0;
        qDebug()<<"ZBCMD.size="<<ZBCmd.size();
        for(int i=0;i<ZBCmd.size();i++)
        {
            qDebug()<<QString::number(ZBCmd.at(i));
            Cheaknum+=ZBCmd.at(i);
        }
        qDebug()<<"Cheaknume="<<QString::number(Cheaknum);
        Cheaknum=Cheaknum&0xff;
        ZBCmd.append(Cheaknum);
    }

   PortStruct targeter;
   foreach (const BasePort *port , m_portList)
   {
        if((port->portParam().type() == "UART" && port->portParam().name() == "Zigbee"))
        {
            targeter = port->portParam();

        }
   }
    emit sendDataSignal(targeter,ZBCmd);
}

void PhoneDevice::ZB3OPInfraredToTestHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{

    Q_UNUSED(target);
    TestInfraredToLearnCmd *zigbee3OPInfraredToTest = qobject_cast<TestInfraredToLearnCmd*>(sharedCmd.data());
    QString NWK=zigbee3OPInfraredToTest->m_nwk;
    quint16 Addr=zigbee3OPInfraredToTest->m_addr;
    qDebug()<<"addr="<<Addr;
    qDebug()<<"nwk="<<NWK;
    Zigbee3InfraredXml *zigbee3InfraredXml = Zigbee3InfraredXml::getInstance();
    Zigbee3ListXml *zigbee3ListXml = Zigbee3ListXml::getInstance();
    quint8 ZigbeeVersion=zigbee3ListXml->ZigbeeVersion().toHex().toInt(0,10);
    Zigbee3InfraredStruct InfraredStruct;
    InfraredStruct.m_PointValue=Addr;
    qDebug()<<"Struct Value="<<InfraredStruct.m_PointValue;
    zigbee3InfraredXml->CopyInfrared.value(Addr,InfraredStruct);
  //  QByteArray Infraredid=InfraredStruct.m_data;

    QByteArray Infraredid=zigbee3InfraredXml->getInfraredID(Addr);
    qDebug()<<"data="<<DataTypeConver::formatString(Infraredid);
    Package package;
    package.setBody(Infraredid);
    package.setFunction(0xD0);



    QByteArray InfraredData=zigbee3InfraredXml->generateData(package);
    QByteArray ZBCmd;
    QByteArray ZBData;
    if(ZigbeeVersion!=5)
    {
       ZBCmd.append(0x51);
       ZBCmd.append(QByteArray::fromHex(NWK.toLatin1()));
       ZBCmd.append(0x01);
       ZBCmd.append((char)0x00);
       ZBCmd.append((char)0x00);
       ZBCmd.append(0X02);
       ZBCmd.append(0x0c);
       ZBCmd.append(0X41);
       ZBCmd.append(0X42);
       ZBCmd.append(InfraredData.size());
       ZBCmd.append(InfraredData);
       ZBCmd.append(0x15);
    }
    else if(ZigbeeVersion==5)
    {
        QByteArray getNewnwk;
        getNewnwk.append(zigbee3OPInfraredToTest->m_nwk.mid(2,1));
        getNewnwk.append(zigbee3OPInfraredToTest->m_nwk.mid(3,1));
        getNewnwk.append(zigbee3OPInfraredToTest->m_nwk.mid(0,1));
        getNewnwk.append(zigbee3OPInfraredToTest->m_nwk.mid(1,1));
        QString newNWK;
        newNWK=getNewnwk;
       ZBCmd.append(0x68);
       ZBCmd.append(char(0x01));
       ZBCmd.append(char(0x00));
       ZBCmd.append(char(0x01));

       ZBData.append(char(0x00));
       ZBData.append(char(0xf1));
       ZBData.append(QByteArray::fromHex(newNWK.toLatin1()));

       ZBData.append(InfraredData.size());
       ZBData.append(InfraredData);
       if(ZBData.size()<0xff)
       {
           ZBCmd.append(char(0x00));
       }

       ZBCmd.append(ZBData.size());
       ZBCmd.append(ZBData);
       quint16 Cheaknum=0;
       for(int i=0;i<ZBCmd.size();i++)
       {
           Cheaknum+=ZBCmd.at(i);
       }
       Cheaknum=Cheaknum&0xff;
       ZBCmd.append(Cheaknum);
    }
   qDebug()<<"ZBCMD.size="<<ZBCmd.size();

   PortStruct targeter;
   foreach (const BasePort *port , m_portList)
   {
        if((port->portParam().type() == "UART" && port->portParam().name() == "Zigbee"))
        {
            targeter = port->portParam();

        }
   }
    emit sendDataSignal(targeter,ZBCmd);

}

void PhoneDevice::ZB3OPInfraredToSaveHandle(PortStruct target, QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(target);
    SaveInfraredToLearnCmd *saveInfraredToLearnCmd = qobject_cast<SaveInfraredToLearnCmd*>(sharedCmd.data());
    QByteArray NWK=saveInfraredToLearnCmd->m_nwk;
    quint16 Value=saveInfraredToLearnCmd->m_Value;
    QByteArray Data;
    Data.append(NWK);
    Data.append(Value);
    Zigbee3InfraredXml *zigbee3InfraredXml = Zigbee3InfraredXml::getInstance();
    Zigbee3InfraredStruct InfraredStruct;
    InfraredStruct=zigbee3InfraredXml->CopyInfrared.value(Value,InfraredStruct);
    InfraredStruct.m_name=saveInfraredToLearnCmd->m_Name;
   // QByteArray Infraredid=InfraredStruct.m_data;
    if(zigbee3InfraredXml->modify(Value,InfraredStruct)==true)
    {
        LogicCloudDataFunc *logicCloudDataFunc=new  LogicCloudDataFunc();
        logicCloudDataFunc->setData(Data);
        logicCloudDataFunc->setDataFunctionCode(0x5e);
        logicCloudDataFunc->setSourceDevice(this->name());
        QSharedPointer<BaseFunc> sharedlogicCloudDataFuncFunc(logicCloudDataFunc);
        emit transferFuncSignal(sharedlogicCloudDataFuncFunc);
    }

    qDebug()<<"Save NOW";



}


void PhoneDevice::LogicCloudDataFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{
    LogicCloudDataFunc *logicCloudDataFunc=qobject_cast<LogicCloudDataFunc*>(sharedFunc.data());
    //qDebug()<<"logicCloudDataFunc-datafunction="<<logicCloudDataFunc->dataFunctionCode();
    if(!m_WaitBackMap.contains(logicCloudDataFunc->dataFunctionCode()))
    {
        return;
    }
   Package package=m_WaitBackMap.value(logicCloudDataFunc->dataFunctionCode(),package);
   //qDebug()<<"PackageNULL";

        m_WaitBackMap.remove(logicCloudDataFunc->dataFunctionCode());
        //qDebug()<<"Package is not NULL";
        package.setBody(logicCloudDataFunc->getData());
        package.setLength(logicCloudDataFunc->getData().size());
        package.setFunction(logicCloudDataFunc->dataFunctionCode());
        if(logicCloudDataFunc->dataFunctionCode()==0x46)
        {
            quint16 newID=package.id()+1;
            package.setId(newID);
            m_WaitBackMap.insert(0x46,package);
        }
        if(logicCloudDataFunc->dataFunctionCode()==0x5b)
        {
            quint16 newID=package.id()+1;
            package.setId(newID);
            m_WaitBackMap.insert(0x5b,package);
        }
        if(logicCloudDataFunc->dataFunctionCode()==0x5E)
        {
            quint16 newID=package.id()+1;
            package.setId(newID);
            m_WaitBackMap.insert(0x5E,package);
        }
        QByteArray sendData=cloudProtocol->generateData(package);
        emit sendDataSignal(package.portStruct(),sendData);
}

void PhoneDevice::phoneToallocationCmdHandle(PortStruct source,QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(sharedCmd);
    qDebug()<<"allocation now ------------------";
    quint16 num=0;
    QByteArray bodydata;
    QByteArray body;
    HeartBestList *HeartBestlist=HeartBestList::GetInstance();
    QList<HeartBestData> heartBestDataList=HeartBestlist->m_HeartBestDataList;
    foreach(HeartBestData getData,heartBestDataList)
    {
        num++;
        bodydata.append(DataTypeConver::intToByteArray(getData.MAC().size(),2));
        bodydata.append(getData.MAC());
    }
    if(num==0)
    {
        qDebug()<<"no have cmd";
        return;
    }
    body.append(DataTypeConver::intToByteArray(num,2));
    body.append(bodydata);
    Package package;
    package.setBody(body);
    package.setFunction(0x4E);
    package.setId(0x01);
    QByteArray AllocationCmd=cloudProtocol->generateData(package);

    emit sendDataSignal(source,AllocationCmd);
}


void PhoneDevice::QueryOtherEquipmentHandle(PortStruct target,QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(sharedCmd);
     OtherEquipmentXml *otherEquipmentXml = OtherEquipmentXml::getInstance();
     QList<PointSwitchUdpStruct> EquipmentList=otherEquipmentXml->m_pointSwitchUdpList;
     foreach(const PointSwitchUdpStruct Struct,EquipmentList)
     {
         quint16 namesize=Struct.Name().toUtf8().size();
         quint16 addr=Struct.Addr();
         QByteArray getData;
         getData.append(namesize>>8);
         getData.append(namesize);
         getData.append(Struct.Name());
         getData.append(addr>>8);
         getData.append(addr);
         Package queryDataPackage;
         queryDataPackage.setBody(getData);
         queryDataPackage.setLength(getData.size());
         queryDataPackage.setFunction(0x51);
         queryDataPackage.setId(0x01);
         QByteArray sendData=cloudProtocol->generateData(queryDataPackage);
         emit sendDataSignal(target,sendData);
     }
}
